<?php

namespace Lowpress\PressExtensionsBundle\Feeds;

use Lowpress\PressBundle\Feeds\IFeedGatherer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Lowpress\PressExtensionsBundle\Entity\RSS;

class RSSFeedGatherer implements IFeedGatherer
{


  private $url;

  public function __construct($url)
  {
    $this->url = $url;
  }

  public function gather(ContainerInterface $container)
  {
    $doctrine = $container->get("doctrine");
    $rss_repository = $doctrine->getRepository('LowpressPressExtensionsBundle:RSS');
    $em = $doctrine->getEntityManager();
    $last_rss = $rss_repository->findOneBy(array(), array('created', 'DESC'));


    $f = new \DOMDocument();
    $f->load($this->url);
    foreach ($f->getElementsByTagName("item") as $p)
    {

      $date = new \DateTime($p->getElementsByTagName("pubDate")->item(0)->nodeValue);
      $date->setTimeZone(new \DateTimeZone(date_default_timezone_get()));

      if (!$last_rss || ($last_rss && $date > $last_rss->getCreated()))
      {
        $rss = new RSS();
        $rss->setLink($p->getElementsByTagName("link")->item(0)->nodeValue);
        $rss->setTitle($p->getElementsByTagName("title")->item(0)->nodeValue);
        $rss->setCreated($date);
        $em->persist($rss);
      }
    }
    $em->flush();
  }

}

?>